<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true"><block slot="backText">返回</block>
			<block slot="content">创建团体赛事</block>
		</cu-custom>
		<view class="create-tm-tips">带*为必填项</view>
		<view class="create-tm-info bg-white">
			<view class="cu-form-group" style="display: block;">
				<view class="flex permates">
					<view class="create-tm-title" style="width: 60%;">比赛项目</view>
					<button class="bg-blue round sm create-tm-btn" @click="addsub" data-target="addsubModal">添加</button>
					<button class="bg-blue round sm create-tm-btn" @click="delsub">删除</button>
				</view>
				<checkbox-group class="subgroup" @change="del_sub">
					<view class="flex"  v-for="(item, index) in sub_list" :key="index" >
						<label><checkbox :checked="item.name==''?true:false" :value="item.name"/>第{{index+1}}场:{{item.name}}</label>
						<input placeholder="备注" v-model="item.value" class="input remark"></input>
					</view>
					<label></label>
				</checkbox-group>
			</view>
			
			<view class="cu-modal" :class="submodalName=='addsubModal'?'show':''" >
				<view class="cu-dialog" @tap.stop="">
					<view class="cu-bar bg-white">
						<view class="action text-blue" @tap="hidesubModal">取消</view>
						<view class="action text-green" @click="suresubModal">确定</view>
					</view>
					<radio-group class="block" @change="subChange">
						<view class="cu-list menu text-left">
							<view class="cu-item" v-for="(item,index) in sblist" :key="index">
								<label class="flex justify-between align-center flex-sub">
									<view class="flex-sub">{{item}}</view>
									
									<radio class="round" :class="radio==item?'checked':''" :checked="radio==item?true:false"
									 :value="item"></radio>
								</label>
							</view>
						</view>
					</radio-group>
				</view>
			</view>
			
			<view class="cu-form-group" style="display: block;">
				<view class="create-tm-title permates">赛制类型</view>
				<view>
					<view class="ruletype flex">
						<radio-group @change="ruletypechange">
							<label ><radio :class="ruletype=='1'?'checked':''" :checked="radio=='1'?true:false" value="1" />淘汰赛</label>
							<label ><radio :class="ruletype=='2'?'checked':''" :checked="radio=='2'?true:false"  value="2" />先小组循环后淘汰</label>
							<label ><radio :class="ruletype=='3'?'checked':''" :checked="radio=='3'?true:false"  value="3" />大循环</label>
						</radio-group>
					</view>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">赛事名称</view>
				<input class="text-right" placeholder="输入名称" v-model="name" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">比赛城市</view>
				<picker mode="region" @change="RegionChange" :value="region">
					<view class="picker">
						{{region[0]}}，{{region[1]}}，{{region[2]}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">赛事地点</view>
				<input class="text-right" placeholder="输入详细地点" @focus="addchange" v-model="address" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">比赛开始时间</view>
				<picker mode="date" :value="sdate"  @change="sDateChange">
					<view class="picker">
						{{sdate}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">比赛结束时间</view>
				<picker mode="date" :value="edate"  @change="eDateChange">
					<view class="picker">
						{{edate}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">报名截止时间</view>
				<picker mode="date" :value="joinedate"  @change="joineDateChange">
					<view class="picker">
						{{joinedate}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group" style="display: block;">
				<view class="flex permates">
					<view class="create-tm-ntitle">报名限定(最多5个本地俱乐部/协会)</view>
					<button class="bg-blue round sm create-tm-btn" @click="addper" data-target="addModal">添加</button>
					<button class="bg-blue round sm create-tm-btn" @click="delper">删除</button>
				</view>
				
				<checkbox-group class="clubgroup" @change="del_cs">
					<view  v-for="(item, index) in cs_list" :key="index" >
						<label><checkbox :checked="item.id==0?true:false" :value="item.id"/>{{item.name}}</label>
					</view>
					<label></label>
				</checkbox-group>
				
			</view>
			<view class="cu-modal" :class="modalName=='addModal'?'show':''">
				<view class="cu-dialog" @tap.stop="">
					<view class="cu-bar bg-white">
						<view class="action text-blue" @tap="hideModal">取消</view>
						<view class="action text-green" @tap="sureModal">确定</view>
					</view>
					<checkbox-group class="cslist-group" @change="cslist_change">
						<view v-for="(item,index) in cslist" :key="index" class="cslist-view">
							<label><checkbox :checked="item.id==0?true:false" :value="item.id" />{{item.name}}</label>
						</view>
					</checkbox-group>
				</view>
			</view>
			<view class="cu-form-group pwd">
				<view class="create-tm-ntitle">数字密码</view>
				<input class="text-right" placeholder="(4位数)如果没有可不填写" v-model="pwd" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">队伍参赛费用</view>
				<input class="text-right" placeholder="参赛费用" v-model="fee" name="input"></input>
			</view>
			<view class="zzfinfo bg-gray">赛事组织方信息</view>
			<view class="cu-form-group">
				<view class="create-tm-ntitle">主办方名称</view>
				<input class="text-right" placeholder="输入主办方名称" v-model="mainsponsor" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-ntitle">协办方名称</view>
				<input class="text-right" placeholder="输入协办方名称" v-model="secondsponsor" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-ntitle">赞助商</view>
				<input class="text-right" placeholder="输入赞助商名称" v-model="helpsponsor" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">联系人</view>
				<input class="text-right" placeholder="输入姓名" v-model="manager" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="create-tm-title">联系方式</view>
				<input class="text-right" placeholder="输入联系方式" v-model="tel" name="input"></input>
			</view>
			<view class="cu-bar bg-white">
				<view class="action">
					赛事宣传图片(第一张将作为封面)
				</view>
				<view class="action">
					{{imgList.length}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="add-per-title">赛事须知</view>
			<view  class="add-per-title">
				<textarea class="cm-des" maxlength="-1" v-model="needknow" ></textarea>
			</view>
			
			<view class="create-tm-button">
				<button class="bg-blue " @tap="create_tm_sure">确认创建</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad(e){
			this.userid=uni.getStorageSync("uid");
			this.openid=uni.getStorageSync('openid');
			console.log(this.userid);
			if(this.userid.length<=0 || this.openid.length<=0){
				uni.showModal({
				    title: '提示',
				    content: '您暂未登陆,是否马上登陆',
				    success: function (res) {
				        if (res.confirm) {
				          uni.navigateTo({
				          	  url:"/pages/tennis/user/index?isback=1"
				          })
				        } else if (res.cancel) {
				           uni.navigateBack({
				           	
				           })
				        }
				    }
				});
				return;
			}
			
			
		},
		data() {
			return {
				
				userid:"",
				openid:"",
				type:1,
				radio: 'radio0',
				region:['福建省','福州市','闽侯县'],
				imgList: [],
				uploadimg:"",
				modalName: null,
				submodalName:null,
				sub_list:[],
				del_subs:[],
				sblist:['男单','女单','男双','女双','混双'],
				//subids:'',
				txtArDes: '',
				sdate:this.formatDate(new Date(new Date().setDate(new Date().getDate()+1))),
				edate: this.formatDate(new Date(new Date().setDate(new Date().getDate()+1))),
				joinedate:this.formatDate(new Date()),
				ruletype:1,
				cs_list:[],
				cslist:[],
				ids:'',
				delids:[],
				chooselist:[],
				name:"",
				address:"",
				pwd:"",
				fee:"",
				mainsponsor:"",
				secondsponsor:"",
				helpsponsor:"",
				needknow:"",
				manager:"",
				tel:"",
				longitude:'',
				latitude:''
			}
		},
		methods: {
			addchange(e){
				uni.chooseLocation({
					success:(res)=>{
						if(res.address.indexOf("省")>0){
							this.region[0]= res.address.split("省")[0]+"省";
							this.region[1]=res.address.split("省")[1].split("市")[0]+"市";
						}
						else if(res.address.indexOf("自治区")>0){
							this.region[0]= res.address.split("自治区")[0]+"自治区";
							this.region[1]=res.address.split("自治区")[1].split("市")[0]+"市";
						}
						else if(res.address.indexOf("特别行政区")>0){
							this.region[0]= res.address.split("特别行政区")[0]+"特别行政区";
							this.region[1]=res.address.split("特别行政区")[0]+"特别行政区";
						}
						this.address=res.name;
						this.longitude=res.longitude;
						this.latitude=res.latitude;
					}
				})
			},
			subChange(e){
				this.radio=e.detail.value
			},
			addsub(e){
				this.submodalName=e.currentTarget.dataset.target;
				
			},
			delsub(e){
				let _this=this;
				//this.submodalName=null;
				if(_this.del_subs.length<=0){
					uni.showModal({
					    title: '提示',
					    content: '请选择要移除的项目',
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
				}else{
					uni.showModal({
					    title: '提示',
					    content: '是否确认移除?',
					    success: function (res) {
					        if (res.confirm) {
					           for(let i = 0;i<_this.del_subs.length;i++){
								   for(let j=0;j<_this.sub_list.length;j++){
									   if(_this.sub_list[j]==_this.del_subs[i]){
										   _this.sub_list.splice(j,1);
									   }
								   }
							   }
					        } else if (res.cancel) {
					           
					        }
					    }
					});
				}
				
			},
			hidesubModal(e){
				this.submodalName = null
			},
			suresubModal(e){
				if(this.sub_list.length<=0){
					this.sub_list=[{name:this.radio,value:''}];
				}else{
					this.sub_list.push({name:this.radio,value:''});
				}
				this.submodalName=null;
			},			
			del_sub(e){
				this.del_subs=e.detail.value;
				
			},
			formatDate(date){
				var y = date.getFullYear();  
				var m = date.getMonth() + 1;  
				m = m < 10 ? '0' + m : m;  
				var d = date.getDate();  
				d = d < 10 ? ('0' + d) : d;  
				return y + '-' + m + '-' + d;  
			},
			
			RegionChange(e){
				
				this.region=e.detail.value
			},
			sDateChange(e){
				this.sdate=e.detail.value
			},
			eDateChange(e){
				this.edate=e.detail.value
			},
			joineDateChange(e){
				this.joinedate=e.detail.value
			},
			ruletypechange(e){
				this.ruletype = e.detail.value
			},
			addper(e){
				
				let city = this.region[1]
				this.chooselist="";
				uni.request({
					url:'https://www.52tennis.cn/Club_Soci/GetListByCity',
					data:{
						city:city,
						ids:this.ids
					},
					success: (data) => {
						console.log(data);
						if(data.data.result==1 && data.data.returnjson.length>0){
							this.modalName = e.currentTarget.dataset.target
							this.cslist=data.data.returnjson;
						}else{
							uni.showModal({
							    title: '提示',
							    content: '本地暂无可添加俱乐部/协会',
							    success: function (res) {
							        if (res.confirm) {
							           this.modalName = null
							        } else if (res.cancel) {
							           this.modalName = null
							        }
							    }
							});
						}
					},
					complete: () => {
						
					}
				})
				
			},
			hideModal(e) {
				this.modalName = null
			},
			delper(e){
				let _this = this;
				if(_this.delids.length>0){
					uni.showModal({
					    title: '提示',
					    content: '是否确定移除俱乐部/协会',
					    success: function (res) {
					        if (res.confirm) {
								let idss=_this.ids.split(";");
								console.log(_this.delids);
								for(let j=0 ;j<_this.delids.length;j++){
									for(let i = 0 ;i<idss.length;i++){
										if(_this.delids[j]==idss[i]){
											idss.splice(i,1);
											break;
										}else{
											continue;
										}
									}
								}
								if(idss.length>0){
									_this.ids="";
									for(let i=0;i<idss.length;i++){
										_this.ids+=idss[i]+";";
									}
									_this.ids=_this.ids.substring(0,_this.ids.length-1);
								}else{
									_this.ids="";
								}
								for(let j=0 ;j<_this.delids.length;j++){
									for(let i=0;i<_this.cs_list.length;i++){
										if(_this.delids[j]==_this.cs_list[i].id){
											_this.cs_list.splice(i,1);
										}
									}
								}
								
					        } else if (res.cancel) {
								
					        }
					    }
					});
				}else{
					uni.showModal({
					    title: '提示',
					    content: '请勾选要移除的俱乐部/协会',
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}
			},
			cslist_change(e){
				this.chooselist=e.detail.value;
			},
			sureModal(e){
				let _this = this;
				
				let oldids=_this.ids.split(";");
				if(oldids.length+_this.chooselist.length>5){
					uni.showModal({
					    title: '提示',
					    content: '最多只能添加5个本地俱乐部/协会',
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}
				
				for(let i = 0;i<_this.chooselist.length;i++){
					if(_this.ids.length>0){
						_this.ids+=";"+_this.chooselist[i]+";";
					}else{
						_this.ids+=_this.chooselist[i]+";";
					}
					if(_this.ids.length>0){
						_this.ids=_this.ids.substring(0,_this.ids.length-1);
					}
					let new_list= _this.cs_list;
					for(let j = 0;j<_this.cslist.length;j++){
						if(_this.chooselist[i]==_this.cslist[j].id){
							if(new_list==null || new_list.length<=0){
								_this.cs_list=[{"name":_this.cslist[j].name,"id":_this.cslist[j].id}];
							}else{
								_this.cs_list.push(_this.cslist[j]);
							}
							
						}
					}
				}
				console.log()
				_this.modalName=null;
			},
			del_cs(e){
				this.delids = e.detail.value;
			},
			
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						uni.uploadFile({
							url: 'https://www.52tennis.cn/ImgUpload/uploadimg', //仅为示例，非真实的接口地址
							filePath: res.tempFilePaths[0],
							fileType:'image',
							name: 'data',
							success: (uploadFileRes) => {
								let result = JSON.parse(uploadFileRes.data)
								console.log("结果:"+result.result)
								if(result.result==1){
									console.log("1");
									if(this.uploadimg.length>0){
										this.uploadimg=this.uploadimg+";"+result.returnjson;
									}else{
										this.uploadimg=result.returnjson;
									}
									console.log("11"+this.uploadimg);
								}
								console.log(uploadFileRes.data);
							}
						});
						
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '再看看',
					confirmText: '是的',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
							let imgs = this.uploadimg.split(";");
							let newimglist = "";
							for(let i = 0;i<imgs.length;i++){
								if(i==e.currentTarget.dataset.index){
									
								}else{
									newimglist+=imgs[i]+";";
								}
							}
							if(newimglist.length>0){
								this.uploadimg=newimglist.substring(0,newimglist.length-1);
							}else{
								this.uploadimg="";
							}
						}
					}
				})
			},
			create_tm_sure(e){
				
				let subbs="";
				if(this.sub_list.length<=0){
					uni.showModal({
					    title: '创建失败',
					    content: "请添加比赛项目",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}else{
					for (let i=0 ;i<this.sub_list.length;i++) {
						subbs+=this.sub_list[i].name+":"+this.sub_list[i].value+";";
					}
				}
				if(subbs.length>0){
					subbs = subbs.substring(0,subbs.length-1);
				}
				
				
				if(this.name.length<=0 || this.fee.length<=0 || this.manager.length<=0 || this.tel.length<=0 || this.address.length<=0 ){
					uni.showModal({
					    title: '创建失败',
					    content: "带*信息请填写完整",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}
				var numreg =/^[0-9]*$/;
				if(!numreg.test(this.fee)){
					uni.showModal({
					    title: '创建失败',
					    content: "报名费用错误,只能输入整数",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}
				var reg=/^1[3456789]\d{9}$/;
				if(!reg.test(this.tel)){
				//var mobilereg = new RegExp("^1[3456789]\d{9}$");
				//if(!mobilereg.test(this.cs_managetel)){
					uni.showModal({
					    title: '创建失败',
					    content: "联系人手机号输入错误",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
					return;
				}
				
				
				if(new Date(this.edate).getTime()-new Date(this.sdate).getTime()<0){
					uni.showModal({
					    title: '创建失败',
					    content: "比赛结束日期应当大于等于比赛结束日期",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
				}
				
				if(new Date(this.sdate).getTime()-new Date(this.joinedate).getTime()<0){
					uni.showModal({
					    title: '创建失败',
					    content: "报名截至日期应当小于比赛开始日期",
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
				}
				
				let timelength = ((new Date(this.edate).getTime()-new Date(this.sdate).getTime())/60/60/1000/24) +1;
				let sclist="";
				if(this.cs_list.length>0){
					for(let i =0 ;i<this.cs_list.length;i++){
						sclist+=this.cs_list[i].id+",";
					}
				}
				if(sclist.length>0){
					sclist= sclist.substring(0,sclist.length-1);
				}
				
				uni.request({
					url:"https://www.52tennis.cn/Match/InsertMatch",
					header:{
						'Content-Type': 'application/json;charset=UTF-8' //自定义请求头信息
					},
					method:'POST',
					
					data: {
						'userid':this.userid,
						'imgurl':this.uploadimg,
						'name':this.name,
						'fee':this.fee,
						'match_type':2,
						'city':this.region[1],
						'address':this.region[2]+this.address,
						'match_subject':subbs,
						'startime':this.sdate,
						'continueday':timelength,
						'joinendtime':this.joinedate+" 23:59:59",
						'connect_name':this.manager,
						'connect_tel':this.tel,
						'endtime':this.edate+" 23:59:59",
						'province':this.region[0],
						'main_sponsor':this.mainsponsor,
						'second_sponsor':this.secondsponsor,
						'help_sponsor':this.helpsponsor,
						'need_know':this.needknow,
						'haspwd':this.pwd.length>0?1:0,
						'pwd':this.pwd,
						'limit_club':sclist,
						'rule_type':this.ruletype,
						'double_type':1,
						'showTitle':'1',
						'longitude':this.longitude,
						'latitude':this.latitude
					
						
					},success:(data)=> {
						console.log(data);
						if(data.data.result==1){
							uni.showToast({
								title: '创建成功',
								icon: 'success',
								mask: true,
								duration: 3000
							})
							setTimeout(function(){
								uni.navigateTo({
									url:"/pages/tennis/match/index"
								})
							},2000)
							
						}else{
							uni.showModal({
							    title: '创建失败',
							    content: data.data.msg+",是否继续创建",
							    success: function (res) {
							        if (res.confirm) {
							           
							        } else if (res.cancel) {
							           uni.navigateTo({
							           		url:"/pages/tennis/match/index"
							           })
							        }
							    }
							});
						}
					}
				})
			}
		}
	}
</script>

<style>
.create-tm-tips{
		padding-left: 30rpx;
		height: 40rpx;
		font-size: 28rpx;
		color: #ED1C24;
	}
	.add-per-title{
		padding:0rpx 30rpx;
		margin-top:15rpx;
	}
	.create-tm-title{
		margin-right: 30rpx;
	}
	.create-tm-title::before{
		content: '*';
		color: #ED1C24;
	}
	.create-tm-ntitle{
		max-width: 65%;
	}
	.create-tm-ntitle::before{
		content: '*';
		color: white;
	}
	.ruletype radio{
		transform:scale(0.6);
		padding-left: 15rpx;
	}
	.subgroup{
		margin-top:15rpx;
	}
	
	.subgroup checkbox{
		transform:scale(0.6);
		padding-left: 5rpx;
		
	}
	.clubgroup checkbox{
		transform: scale(0.7);
		padding:5rpx;
	}
	.zzfinfo{
		padding:10rpx 30rpx;
	}
	.permates{
		padding:10rpx 0rpx;
	}
	.cm-des{
		border: 1px solid #808080;
		padding:15rpx;
		border-radius: 15rpx;
		width:100%;
		height: 180rpx;
		overflow: auto;
		word-break: break-all;
	}
	.create-tm-btn{
		font-size: 24rpx;
	}
	.cslist-group{
		text-align: left;
	}
	.cslist-view{
		padding:15rpx 50rpx;
	}
	.pwd{
		border-top: 1rpx solid #eee;
	}
	.create-tm-button{
		padding:30rpx;
		padding-bottom: 50rpx;
	}
	.remark{
		border:1rpx solid #8799A3;
		height: 35rpx;
		line-height: 35rpx;
		margin-left: 15rpx;
		font-size: 26rpx;
		max-width: 250rpx;
		border-radius: 10rpx;
		padding-left: 10rpx;

	}
</style>
